package cn.lijida.weiwei.favor.commons.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;

import cn.lijida.weiwei.favor.commons.constant.Conf;
import cn.lijida.weiwei.favor.commons.utils.ReturnT;
import cn.lijida.weiwei.favor.commons.utils.SpringContextUtils;
import cn.lijida.weiwei.favor.modules.sys.service.IFavorTokenService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoginIdFilter extends HttpServlet implements Filter {

    /**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -9057723925770378701L;

	private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private String logoutPath;
    
    private String excludedPaths;
    
    private IFavorTokenService tokenService = SpringContextUtils.getBean("favorTokenServiceImpl", IFavorTokenService.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        logoutPath = filterConfig.getInitParameter(Conf.LOGOUT_PATH);
        
        excludedPaths = filterConfig.getInitParameter(Conf.EXCLUDED_PATHS);

        log.info("LoginIdFilter init.");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // make url
        String servletPath = req.getServletPath();
        
        String token = req.getHeader(Conf.TOKEN);
        String deviceId = req.getHeader(Conf.DEVICE_ID);
        Long memberId = null;
        
        if(StringUtils.isNotBlank(token) && StringUtils.isNotBlank(deviceId)){
        	memberId = tokenService.getMemberId(token,deviceId);
        	if(memberId != null){
            	request.setAttribute(Conf.LOGIN_ID, memberId);
            }
        }

        // excluded path check
        if (excludedPaths!=null && excludedPaths.trim().length()>0) {
            for (String excludedPath:excludedPaths.split(",")) {
                String uriPattern = excludedPath.trim();

                // 支持ANT表达式
                if (antPathMatcher.match(uriPattern, servletPath)) {
                    // excluded path, allow
                    chain.doFilter(request, response);
                    return;
                }

            }
        }

        // logout filter
        if (logoutPath!=null
                && logoutPath.trim().length()>0
                && logoutPath.equals(servletPath)) {

            // logout
        	tokenService.logout(token,deviceId);
            // response
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":"+ReturnT.SUCCESS_CODE+", \"msg\":\"\"}");

            return;
        }

        if(memberId == null){
        	res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":"+ReturnT.NOT_LOGIN_CODE+", \"msg\":\""+ ReturnT.NOT_LOGIN_MSG +"\"}");
            return;
        }

        // already login, allow
        chain.doFilter(request, response);
        return;
    }


}
